package com.ruoyi.controller.redismq.config;

import com.ruoyi.controller.redismq.Receiver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;



@Configuration
@AutoConfigureAfter({Receiver.class})
public class SubscriberConfig {

//    //向容器放入接收对象
//    @Bean
//    public Receiver receiver(CountDownLatch latch) {
//        return new Receiver(latch);
//    }
//    //提供给接收对象实体
//    @Bean
//    public CountDownLatch latch() {
//        return new CountDownLatch(1);
//    }
    //redis
    @Bean
    public StringRedisTemplate stringRedisTemplate(@Autowired RedisConnectionFactory connectionFactory) {
        return new StringRedisTemplate(connectionFactory);
    }

    /**
     * 注入消息监听适配器
     */
    @Bean
    public MessageListenerAdapter getMessageListenerAdapter(Receiver receiver){
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }

    /**
     * 注入消息监听容器
     */
    @Bean
    public RedisMessageListenerContainer getRedisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory, MessageListenerAdapter messageListenerAdapter){
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();

        redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);
        //new PattenrnTopic跟消息发布者的要一致; 例如消息发布者为stringRedisTemplate.convertAndSend("notify", message);则对应以下
        redisMessageListenerContainer.addMessageListener(messageListenerAdapter, new PatternTopic("notify"));

        return redisMessageListenerContainer;
    }

}

